package com.foreveross.action.common;


import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.foreveross.common.CommonUtil;
import com.foreveross.common.Exception.ExceptionConstant;
import com.foreveross.util.FileUtil;
import com.foreveross.vo.common.FileVo;
import com.foreveross.vo.common.ResultVo;

@Controller
@RequestMapping(value="/common/CommonController")
public class CommonController {

	private Logger log = Logger.getLogger(CommonController.class);

	/**
	 * 图片上传
	 * 
	 * @param request
	 * @param response
	 * @param file
	 */
	@RequestMapping(value = "/uploadImg")
	public void uploadImg(HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam("Img") MultipartFile file,String folderName) {
		ResultVo resultVo = new ResultVo();
		try {
			String str = "";
			if(null != folderName && !"".equals(folderName)) str = folderName+"/";
			resultVo = FileUtil.uploadFile(request, file, str , true);
			if (resultVo.isSuccess()){
				FileVo fileVo = new FileVo((String)resultVo.getData(),
						CommonUtil.getHttpBasePath(request)+ resultVo.getData());
				
				resultVo.setData(fileVo);
			}else
				resultVo.setMessage(ExceptionConstant.getExceptionMessage((String) resultVo.getMessage())); 
		} catch (Exception e) {
			resultVo.setSuccess(false);
			resultVo.setMessage("上传文件失败");
		}
		CommonUtil.PrintWriterResultVoWithJSON(response, resultVo);

	}

	/**
	 * 富文本编辑器上传文件
	 * 
	 * @param request
	 * @param response
	 * @param file
	 */
	@RequestMapping(value = "/uploadRichTextImg")
	public void uploadRichTextImg(HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam("upload") MultipartFile file) {
		try {

			String callback = request.getParameter("CKEditorFuncNum");
			ResultVo resultVo = FileUtil
					.uploadFile(request, file, "richTextImg/", true);

			PrintWriter out = response.getWriter();
			// 返回"图像"选项卡并显示图片 request.getContextPath()为web项目名
			out.println("<script type=\"text/javascript\">");
			if (resultVo.isSuccess())
				// 必须跟 http://的绝对路径
				out.println("window.parent.CKEDITOR.tools.callFunction("
						+ callback + ",'" + CommonUtil.getHttpBasePath(request)
						+ resultVo.getData() + "','')");
			else
				out.println("window.parent.CKEDITOR.tools.callFunction("
						+ callback
						+ ",'','"
						+ ExceptionConstant
								.getExceptionMessage((String) resultVo
										.getMessage()) + "')");
			out.println("</script>");
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
